package com.qingyun.video.service.impl;

import com.alibaba.fastjson.JSON;
import com.qingyun.apis.schedule.IScheduleClient;

import com.qingyun.model.common.dtos.R;
import com.qingyun.model.common.enums.TaskTypeEnum;
import com.qingyun.model.schedule.dtos.Task;
import com.qingyun.model.video.pojos.Video;
import com.qingyun.video.service.AutoScanService;
import com.qingyun.video.service.VideoTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import utils.common.ProtostuffUtil;

import javax.annotation.Resource;
import java.util.Date;


@Service
@Slf4j
public class TaskServiceImpl implements VideoTaskService {

    @Resource
    private IScheduleClient scheduleClient;

    /**
     * 添加任务到延迟队列中
     * @param id
     * @param publishTime
     */
    @Override
    @Async
    public void addToTask(Long id, Date publishTime) {
        log.info("添加任务到延迟队列中----begin");
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        Video video =new Video();
        video.setId(id);
        task.setParameters(ProtostuffUtil.serialize(video));
        scheduleClient.addTask(task);
        log.info("添加任务到延迟队列中----end");
    }

    @Resource
    private AutoScanService autoScanService;
    /**
     * 消费任务，审核文章
     */
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanByTask() {
        log.info("消费任务，审核文章");
        R responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode().equals(1)&&responseResult.getData()!=null){
            log.error("消费任务，审核文章-----error");
            Task task = JSON.parseObject(JSON.toJSONString(responseResult.getData()), Task.class);
            Video video = ProtostuffUtil.deserialize(task.getParameters(), Video.class);
            autoScanService.autoScanVideo(video.getId());
        }
    }
}
